module SentientModel
  def self.included(base)
    base.extend(ClassMethods)
  end

  def make_current
    self.class.current = self
  end

  def current?
    self.class.has_current? && self == self.class.current
  end

  module ClassMethods
    def current
      Thread.current[sentient_model_name]
    end

    def current=(m)
      unless (m.is_a?(self) || m.nil?)
        raise(ArgumentError, "Expected an object of class '#{self}', got #{m.inspect}")
      end
      Thread.current[sentient_model_name] = m
    end

    def has_current?
      !self.current.nil?
    end

  private
    def sentient_model_name
      self.name.downcase.to_sym
    end
  end
end
